#!/bin/bash
user=$1
servers_file=$2
outputdir=$3
scriptfile=$4
keyfile=$5

jobcount="0"
#for each server, demon execute the ssh command, and print the output into a log file
for server in `cat ${servers_file}` ; do
logfile=${outputdir}/${server}.log
donefile="${outputdir}/.done"
#clean the done file
cat "">${donefile}
echo "INFO:	Server - ${server}, user - ${user}, script - ${scripts}, output - ${logfile}"
echo "	"
back_cmd="./ssh_exec_file ${user} ${server} ${scriptfile} ${keyfile}"
printf "${back_cmd}"
./back.sh ${logfile} "${back_cmd}" "${donefile}" &
jobcount=`expr ${jobcount} + 1`
done

#check if all job stoped, by watch .done file stopped appending
echo ""
echo "INFO:	Start to check if all jobs are finished, Total job count - ${jobcount}"
loopcount=0
maxloopcount=60
unit=5
while : ;
do
finishedjob=`wc -l ${donefile}|cut -d' ' -f1`
if [ "${finishedjob}" = "${jobcount}" ];
then
echo "INFO:	COOL! All jobs done!"
break
fi
#continue to check the left jobs
loopcount=`expr "${loopcount}" + "1"`
echo "INFO:	Finished job count ${finishedjob}, time used `expr ${loopcount} \"*\" ${unit}` seconds."
if [ "${loopcount}" -gt "${maxloopcount}" ];
then
echo "WARN:	Runing too long time, will exit, please check by your self."
break
else
echo "INFO:	Sleep for ${unit} seconds..."
sleep ${unit}
fi
done 

echo "INFO:	DONE! Find the output in folder ${outputdir}"